import {Buffer} from "buffer";
import {DataUtils} from "./DataUtils";


export class ReverseByteArrayInputStream {

    buf: Buffer;
    pos: number = 0;
    mark: number = 0;
    count: number = 0;

    constructor(buffer: Buffer) {
        this.buf = buffer;
        this.pos = 0;
        this.count = buffer.length;
    }

    read(): number {
        return (this.pos < this.count) ? (this.buf[this.pos++] & 0xff) : -1;
    }

    readoffset(buf: Buffer, offset: number, len: number): number {
        if (buf == null) {
            throw new Error("buf is null");
        } else if (offset < 0 || len < 0 || len > buf.length - offset) {
            throw new Error("array index of bound");
        }
        if (this.pos >= this.count) {
            return -1;
        }
        let avail = this.count - this.pos;
        if (len > avail) {
            len = avail;
        }
        if (len <= 0) {
            return 0;
        }
        this.buf.copy(buf, offset, this.pos, this.pos + len);
        this.pos += len;
        return len;
    }

    available(): number {
        return this.count - this.pos;
    }

}

